package com.mobi.Survey.lib.db;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mobi.Survey.lib.model.AlarmPojo;
import com.mobi.Survey.lib.model.Pojo;

public class AlarmTable extends AbstractTable {

	public static final String TABLE = "survey_alarm";

	public static final String COL_ID = "_id";
	public static final String COL_SURVEY_ID = "survey_id";
	public static final String COL_SURVEY_KEY = "survey_key";
	public static final String COL_START_TIME = "start_time";
	public static final String COL_END_TIME = "end_time";
	public static final String COL_ACTIVE_STATE = "active_state";
	public static final String COL_REPEAT_TYPE = "repeat_type";
	public static final String COL_MESSAGE = "message";
	public static final String COL_IMAGE_URL = "image_url";
	public static final String COL_AUDIO_URL = "audio_url";
	public static final String COL_SEQ_NO = "seq_no";
	public static final String COL_UPPER_LIMIT = "upper_limit";
	public static final String COL_LOWER_LIMIT = "lower_limit";
	public static final String COL_BUTTONS = "buttons";
	public static final String COL_MANUALLY_COMPLETED = "manual_complete";
	public static final String COL_START_TIME_STR = "StartTime";
	public static final String COL_WRT_CURRENT_TIME = "wrt_current_time";
	public static final String COL_INSTALL_TIME = "install_time";

	@Override
	public boolean createTable(SQLiteDatabase sqliteDb) {
		String query = "create table " + TABLE + "( " + COL_ID + " integer primary key autoincrement, " + COL_SURVEY_ID
				+ " varchar not null,  " + COL_SURVEY_KEY + " text, " + COL_START_TIME + " big integer not null, "
				+ COL_END_TIME + " big integer not null, " + COL_ACTIVE_STATE + " integer not null, " + COL_REPEAT_TYPE
				+ " integer default null, " + COL_MESSAGE + " text, " + COL_IMAGE_URL + "  text, " + COL_SEQ_NO
				+ "  big integer not null, " + COL_UPPER_LIMIT + " text, " + COL_LOWER_LIMIT + " text, " + COL_BUTTONS
				+ " text, " + COL_MANUALLY_COMPLETED + " integer not null default 0, " + COL_START_TIME_STR
				+ " text not null, " + COL_AUDIO_URL + " text, " + COL_WRT_CURRENT_TIME + " integer default 0, "+COL_INSTALL_TIME+" big integer not null )";
		sqliteDb.execSQL(query);
		printMessage(query);
		return true;
	}

	public boolean insertRows(List<AlarmPojo> alarms, long surveyId) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		boolean areAdded = true;
		for (AlarmPojo alarm : alarms) {

			ContentValues cv = new ContentValues();
			cv.put(COL_SURVEY_ID, surveyId);
			cv.put(COL_SURVEY_KEY, alarm.getSurveyKey());
			cv.put(COL_START_TIME, alarm.getStart());
			cv.put(COL_ACTIVE_STATE, alarm.isActive());
			cv.put(COL_END_TIME, alarm.getEnd());
			cv.put(COL_IMAGE_URL, alarm.getImageUrl());
			cv.put(COL_MESSAGE, alarm.getMessage());
			cv.put(COL_REPEAT_TYPE, alarm.getRepeatString());
			cv.put(COL_SEQ_NO, alarm.getSequanceNo());
			cv.put(COL_UPPER_LIMIT, alarm.getUpperLimit());
			cv.put(COL_LOWER_LIMIT, alarm.getLowerLimit());
			cv.put(COL_BUTTONS, alarm.getButtons());
			cv.put(COL_START_TIME_STR, alarm.getStartTimeStr());
			cv.put(COL_AUDIO_URL, alarm.getAudioUrl());
			cv.put(COL_WRT_CURRENT_TIME, alarm.isWithRespectToCurrentTime());
			cv.put(COL_INSTALL_TIME, System.currentTimeMillis());
			
			long id = db.insert(TABLE, null, cv);
			areAdded = id >= 0;
			if (!areAdded) {
				break;

			}
		}

		return areAdded;
	}

	@Override
	public long insertRow(Pojo obj) {
		AlarmPojo alarm = (AlarmPojo) obj;
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		ContentValues cv = new ContentValues();
		cv.put(COL_SURVEY_ID, alarm.getSurveyId());
		cv.put(COL_SURVEY_KEY, alarm.getSurveyKey());
		cv.put(COL_START_TIME, alarm.getStart());
		cv.put(COL_ACTIVE_STATE, alarm.isActive());
		cv.put(COL_END_TIME, alarm.getEnd());
		cv.put(COL_IMAGE_URL, alarm.getImageUrl());
		cv.put(COL_MESSAGE, alarm.getMessage());
		cv.put(COL_REPEAT_TYPE, alarm.getRepeatString());
		cv.put(COL_SEQ_NO, alarm.getSequanceNo());

		cv.put(COL_UPPER_LIMIT, alarm.getUpperLimit());
		cv.put(COL_LOWER_LIMIT, alarm.getLowerLimit());
		cv.put(COL_BUTTONS, alarm.getButtons());
		cv.put(COL_START_TIME_STR, alarm.getStartTimeStr());
		cv.put(COL_AUDIO_URL, alarm.getAudioUrl());
		cv.put(COL_WRT_CURRENT_TIME, alarm.isWithRespectToCurrentTime());
		cv.put(COL_INSTALL_TIME, System.currentTimeMillis());
		long id = db.insert(TABLE, null, cv);
		return id;
	}

	@Override
	public boolean deleteRow(long id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int effected = db.delete(TABLE, COL_ID + " = ? ", new String[] { id + "" });
		return effected > 0;
	}

	public void deleteSet(Collection<AlarmPojo> alarms) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		for (AlarmPojo alarm : alarms) {

			db.delete(TABLE, COL_ID + " = ? ", new String[] { alarm.getId() + "" });
		}

	}

	@Override
	public void deleteAllData() {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(TABLE, null, null);
	}

	public AlarmTable() {

	}

	public List<AlarmPojo> getValidAlarmBySurveyId(long surveyId) {
		List<AlarmPojo> alarms = new ArrayList<AlarmPojo>();

		SQLiteDatabase db = dbHelper.getReadableDatabase();

		Cursor cursor = db.query(TABLE, new String[] { COL_ID, COL_MESSAGE, COL_START_TIME, COL_END_TIME,
				COL_ACTIVE_STATE, COL_REPEAT_TYPE, COL_UPPER_LIMIT, COL_LOWER_LIMIT, COL_BUTTONS, COL_START_TIME_STR,
				COL_AUDIO_URL, COL_WRT_CURRENT_TIME ,COL_IMAGE_URL,COL_INSTALL_TIME}, COL_SURVEY_ID + " = ? ", new String[] { surveyId + "" }, null,
				null, COL_START_TIME + " DESC");

		if (null != cursor && cursor.moveToFirst()) {

			do {
				AlarmPojo alarm = new AlarmPojo();

				long id = cursor.getLong(0);
				String message = cursor.getString(1);
				long start = cursor.getLong(2);
				long end = cursor.getLong(3);
				boolean active = cursor.getInt(4) == 1;
				String repeats = cursor.getString(5);
				String upperLimit = cursor.getString(6);
				String lowerLimit = cursor.getString(7);
				String buttons = cursor.getString(8);
				String startTimeStr = cursor.getString(9);
				String audioUrl = cursor.getString(10);
				boolean wrtTime = cursor.getInt(11) == 1;
				String imageUrl = cursor.getString(12);
				long installTime = cursor.getLong(13);

				alarm.setSurveyId(surveyId);
				alarm.setId(id);
				alarm.setMessage(message);
				alarm.setStart(start);
				alarm.setEnd(end);
				alarm.setActive(active);
				alarm.setRepeats(repeats);
				alarm.setUpperLimit(upperLimit);
				alarm.setLowerLimit(lowerLimit);
				alarm.setButtons(buttons);
				alarm.setStartTimeStr(startTimeStr);
				alarm.setAudioUrl(audioUrl);
				alarm.setWithRespectToCurrentTime(wrtTime);
				alarm.setImageUrl(imageUrl);
				alarm.setInstallTime(installTime);

				if (wrtTime) {
					alarm.triggerTImeWithRespectToCurrentTIme();
				}

				alarms.add(alarm);

			} while (cursor.moveToNext());

		}
		cursor.close();

		return alarms;
	}

	public boolean isExist(long alarmId) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		Cursor cursor = db.query(TABLE, new String[] { COL_ID }, COL_ID + " = ? ", new String[] { alarmId + "" }, null,
				null, null);
		long id = -1;
		try {

			if (cursor.moveToFirst()) {
				id = cursor.getLong(0);

			}
		} catch (Exception e) {

		} finally {
			cursor.close();
		}

		return id > 0;

	}

	public AlarmTable(Context ctx) {
		super(ctx);
	}

	public void setWRTCurrentTimeFalseByAlarmId(long alarmId){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COL_WRT_CURRENT_TIME, false);
		db.update(TABLE, cv, COL_ID + " =? ", new String[] { alarmId + "" });
		
	}
	
	public void updateManualClick(long alarmId, boolean isManually) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COL_MANUALLY_COMPLETED, isManually);
		db.update(TABLE, cv, COL_ID + " =? ", new String[] { alarmId + "" });
	}

	public boolean isManuallyClicked(long alarmId) {

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(TABLE, new String[] { COL_MANUALLY_COMPLETED }, COL_ID + " =? ",
				new String[] { alarmId + "" }, null, null, null);
		boolean isManual = false;
		if (null != cursor) {

			if (cursor.moveToFirst()) {
				isManual = cursor.getInt(0) == 1;
			}

			cursor.close();
		}

		return isManual;
	}

	public List<AlarmPojo> getUpComings() {
		// SELECT * FROM survey_alarm where active_state = 1 and (start_time >=
		// 1409511601000 or (repeat_type is not null and end_time <
		// 1419966000000)) order by start_time desc limit 1

		SQLiteDatabase db = dbHelper.getReadableDatabase();

		List<AlarmPojo> alarms = new ArrayList<AlarmPojo>();

		Cursor cursor = db.query(TABLE,

		new String[] { COL_ID, COL_MESSAGE, COL_START_TIME, COL_END_TIME, COL_ACTIVE_STATE, COL_REPEAT_TYPE,
				COL_SURVEY_ID, COL_IMAGE_URL, COL_SEQ_NO, COL_UPPER_LIMIT, COL_LOWER_LIMIT, COL_BUTTONS,
				COL_START_TIME_STR, COL_AUDIO_URL, COL_WRT_CURRENT_TIME , COL_INSTALL_TIME}, COL_ACTIVE_STATE + " = 1  and ( "
				+ COL_START_TIME + " >= ? or ( " + COL_REPEAT_TYPE + " is not null and " + COL_END_TIME + " > ? ))",
				new String[] { System.currentTimeMillis() + "", System.currentTimeMillis() + "" }, null, null,
				COL_START_TIME + " DESC  ");

		if (null != cursor && cursor.moveToFirst()) {
			do {
				AlarmPojo alarm = new AlarmPojo();
				long id = cursor.getLong(0);
				String message = cursor.getString(1);
				long start = cursor.getLong(2);
				long end = cursor.getLong(3);
				boolean active = cursor.getInt(4) == 1;
				String repeats = cursor.getString(5);
				long surveyId = cursor.getLong(6);
				String imageUrl = cursor.getString(7);
				long seqNo = cursor.getLong(8);
				String upperLimit = cursor.getString(9);
				String lowerLimit = cursor.getString(10);
				String buttons = cursor.getString(11);
				String startTimeStr = cursor.getString(12);
				String audioUrl = cursor.getString(13);
				boolean wrtTime = cursor.getInt(14) == 1;
				long installTime = cursor.getLong(15);

				alarm.setSurveyId(surveyId);
				alarm.setId(id);
				alarm.setMessage(message);
				alarm.setStart(start);
				alarm.setEnd(end);
				alarm.setActive(active);
				alarm.setRepeats(repeats);
				alarm.setImageUrl(imageUrl);
				alarms.add(alarm);
				alarm.setSequanceNo(seqNo);
				alarm.setUpperLimit(upperLimit);
				alarm.setLowerLimit(lowerLimit);
				alarm.setButtons(buttons);
				alarm.setStartTimeStr(startTimeStr);
				alarm.setAudioUrl(audioUrl);
				alarm.setWithRespectToCurrentTime(wrtTime);
				alarm.setInstallTime(installTime);

				if (wrtTime) {
					alarm.triggerTImeWithRespectToCurrentTIme();
				}

			} while (cursor.moveToNext());
		}
		cursor.close();

		return alarms;

	}
}
